package graphic;

import filemanager.FileManager;
import graphic.mycomponents.ProgramTab;

import java.util.HashMap;
import java.util.Iterator;

import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import core.Server;

public class FilesTabbedPanel extends JTabbedPane implements ChangeListener {

	protected static FilesTabbedPanel FILESPANEL;
	
	public static String WELCOMETAB = "Welcome!";
	
	HashMap<String, ProgramTab> tabs;
	
	String selectedTab;
	
	public FilesTabbedPanel()
	{
		this.refreshPanel();
	}
	
	public void refreshPanel()
	{
		super.removeAll();
		
		this.tabs = new HashMap<String, ProgramTab>();
		
		HashMap<String, FileManager> programs = Server.getInstance().getPrograms();
		
		FileManager fileManager;
		String programName;
		ProgramTab programTab;
		for (Iterator iterator = programs.keySet().iterator(); iterator.hasNext();) {
			programName = (String) iterator.next();
			if(this.selectedTab == null) this.selectedTab = programName;
			fileManager = programs.get(programName);
			programTab = new ProgramTab(fileManager);
			this.tabs.put(programName, programTab);
			super.addTab(programName, programTab);
			
			System.out.println("HO AGGIUNTO " + programName );
		}
		
		if(this.tabs.isEmpty())
			super.addTab(FilesTabbedPanel.WELCOMETAB, new ProgramTab(null));
		
		super.addChangeListener(this);
	}

	@Override
	public void stateChanged(ChangeEvent e)
	{
	    JTabbedPane tabSource = (JTabbedPane) e.getSource();
	    if(tabSource.getSelectedIndex() == -1) return;
	    
	    FilesTabbedPanel.this.selectedTab = tabSource.getTitleAt(tabSource.getSelectedIndex());	
	}

	public void addProgram(String programName)
	{
		ProgramTab programTab = new ProgramTab(Server.getInstance().getPrograms().get(programName));
		this.tabs.put(programName, programTab);
		super.addTab(programName, programTab);
		
		super.repaint();
	}
	
	public HashMap<String, ProgramTab> getTabs() {
		return tabs;
	}

	public String getSelectedTab() {
		return selectedTab;
	}

	public static synchronized FilesTabbedPanel getInstance()
	{
		if(FILESPANEL == null) FILESPANEL = new FilesTabbedPanel();
		return FILESPANEL;
	}
}
